import React, {PropsWithChildren, useCallback, useEffect, useState} from 'react'
import Taro, {useLoad} from "@tarojs/taro";
import {
    createMarketOrder, MarketOrderDetailResponse,
    marketOrderStatusMap,
    queryMarketOrderInMarket,
    QueryMarketOrderInMarketResponse
} from "../apis/MarketOrderApi";
import {Cell, VirtualList} from "@nutui/nutui-react-taro";
import {OffsetDateTime} from "@js-joda/core";
import {DATE_WITH_HOUR_MINUTE_FORMATER, YEAR_MONTH_DAY_FORMATER} from "../utils/Date";
import {Text} from "@tarojs/components";
import styles from "./marketOrder.module.sass"
import FloatButton from "../components/FloatButton";
import {Add} from "@nutui/icons-react-taro";
import {observer} from "mobx-react";
import employeeStore from "../store/EmployeeStore";
import MyNavigationBar from "../components/MyNavigationBar";
import marketOrderInMarketPageStackStore from "../store/MarketOrderInMarketPageStackStore";
import marketPageStackStore from "../store/MarketPageStackStore";
import {Pageable} from "../utils/Page";

export interface MarketOrderProps extends PropsWithChildren {

}

const MarketOrder: React.FC<MarketOrderProps> = ({}) => {
    const [marketId, setMarketId] = useState<number>()
    const [marketName,setMarketName] = useState<string>()
    const [loading, setLoading] = useState(false)
    const queryWithoutPageable = useCallback(async (pageable:Pageable)=>{
        if (marketId) {
            setLoading(true)
            return queryMarketOrderInMarket(marketId, pageable);
        }else {
            return undefined
        }
    },[marketId])
    const query = useCallback(() => {
        queryWithoutPageable(marketOrderInMarketPageStackStore.pageable).then(response => {
            if (response){
                marketOrderInMarketPageStackStore.appendItems(response.data)
            }
        }).finally(() => {
            setLoading(false)
        });
    }, [queryWithoutPageable, ...marketOrderInMarketPageStackStore.pageable.toDependencyList()]);
    useEffect(() => {
        query()
    }, [query]);
    useEffect(() => {
        marketOrderInMarketPageStackStore.onRemove = async (_,list)=>{
            let response = await queryWithoutPageable(new Pageable(list.length,1));
            if (response){
                marketOrderInMarketPageStackStore.list = marketOrderInMarketPageStackStore.list.concat(response.data.content)
            }
        }
    }, [queryWithoutPageable]);
    useEffect(() => {
        return ()=>{
            marketOrderInMarketPageStackStore.clearList()
        }
    }, []);
    useLoad(params => {
        Taro.setNavigationBarTitle({
            title: params.marketName + "订单"
        })
        setMarketId(parseInt(params.marketId))
        setMarketName(params.marketName)
    });
    return <>
        <MyNavigationBar>卖场订单</MyNavigationBar>
        <VirtualList
            onScroll={() => {
                if (!marketOrderInMarketPageStackStore.last && !loading) {
                    marketOrderInMarketPageStackStore.next()
                }
            }}
            list={marketOrderInMarketPageStackStore.list}
            itemHeight={66}
            itemRender={(item: QueryMarketOrderInMarketResponse) => {
                return <Cell title={<Text
                    className={styles.title}>{`${item.createdBy.name}创建于${item.createdDateTime
                    .toLocalDate()
                    .format(YEAR_MONTH_DAY_FORMATER)}`}</Text>} style={{margin: 0}}
                             extra={marketOrderStatusMap[item.status]}
                             description={`${item.goodsKindAmount}个单品`}
                             onClick={() => {
                                 Taro.navigateTo({
                                     url: `/pages/marketOrderDetail?id=${item.id}`
                                 })
                             }}/>;
            }}/>
        {!!marketId && employeeStore.hasAuthority("卖场_订单_下单") && <FloatButton icon={<Add/>} onClick={async () => {
            async function doCreateMarketOrder(){
                await createMarketOrder(marketId!!).then(response => {
                    const detail:MarketOrderDetailResponse = {
                        id: response.data,
                        createdBy: {...employeeStore.employee!!},
                        createdDateTime: OffsetDateTime.now(),
                        market:{
                            id:marketId!,
                            name:marketName!,
                        },
                        number:"",
                        items:[]
                    }
                    marketOrderInMarketPageStackStore.appendItemByDetail(detail)
                    if(marketPageStackStore.detail){
                        marketPageStackStore.updateDetail({
                            ...marketPageStackStore.detail,
                            orderAmount:marketPageStackStore.detail.orderAmount+1,
                        })
                    }
                    Taro.navigateTo({
                        url: `/pages/marketOrderDetail?id=${response.data}`
                    })
                });
            }
            const waitSubmittedOrder = marketOrderInMarketPageStackStore.list.find(it => it.status === "WAIT_SUBMIT")
            if (!!waitSubmittedOrder) {
                let result = (await Taro.showModal({
                    title: `新增卖场订单确认`,
                    content: `${waitSubmittedOrder.createdBy.id===employeeStore.employee?.id?"你":waitSubmittedOrder.createdBy.name}已经在${waitSubmittedOrder.createdDateTime.format(DATE_WITH_HOUR_MINUTE_FORMATER)}创建的订单,且尚未提交,是否需要创建一个新的订单?`,
                    confirmText:"仍然创建",
                }))
                if (result.confirm){
                    await doCreateMarketOrder()
                }
            }else {
                await doCreateMarketOrder()
            }


        }}/>}
    </>
}

export default observer(MarketOrder)


